package com.ftg.learn.service.impl;

import com.ftg.learn.entity.SysRole;
import com.ftg.learn.mapper.SysRoleMapper;
import com.ftg.learn.mapper.SysRolePermissionMapper;
import com.ftg.learn.mapper.SysUserRoleMapper;
import com.ftg.learn.service.RoleService;
import com.ftg.learn.util.PageEx;
import com.ftg.learn.util.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 布衣
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysRolePermissionMapper rolePermissionMapper;

    @Override
    public R<PageEx<SysRole>> list(String roleName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return R.ok(PageEx.convertToPageEx(new PageInfo<>(roleMapper.list(roleName))));
    }

    @Override
    public R<Integer> add(SysRole role) {
        return roleMapper.add(role) >0 ? R.ok(1) : R.failure();
    }

    @Override
    public R<Integer> update(SysRole role) {
        return roleMapper.update(role) >0 ? R.ok(1) : R.failure();
    }

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public R<Integer> deleteById(Long id) {
        userRoleMapper.deleteByRoleId(id);
        rolePermissionMapper.deleteByRoleId(id);
        return roleMapper.deleteById(id) >0 ? R.ok(1) : R.failure();
    }

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public R<Integer> deleteByIds(List<Long> ids) {
        userRoleMapper.deleteByRoleIds(ids);
        rolePermissionMapper.deleteByRoleIds(ids);
        return R.ok(roleMapper.deleteByIds(ids));
    }
}
